//
//  PointClassListViewController.m
//  fitnessmanage
//
//  Created by wujian on 2018/1/22.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//

#import "PointClassListViewController.h"
#import "TeachClassHeadView.h"
#import "TeachClassTableViewCell.h"
#import "TeachBottomView.h"
#import "PointClassInfoViewController.h"

@interface PointClassListViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)TeachClassHeadView *teachClassHeadView;

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,weak)TeachBottomView *teachBottomView;

@property(nonatomic,strong)NoDataView *noDataView;

@end

@implementation PointClassListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"全部课程";
    
    self.view.backgroundColor = BackGroundColor;
    
    [self createSubView];
    
    [NotificationCenter addObserver:self selector:@selector(setSelectData:) name:@"selectDate" object:nil];
}

-(void)createSubView{
    
    TeachClassHeadView *teachClassHeadView = [[TeachClassHeadView alloc] init];
    
    teachClassHeadView.classType = self.classType;
    
    [teachClassHeadView.timeBtn setTitle:self.date];
    
    teachClassHeadView.startDate = self.date;
    
    [self.view addSubview:teachClassHeadView];
    self.teachClassHeadView = teachClassHeadView;
    
    [teachClassHeadView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.width.mas_equalTo(self.view);
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[TeachClassTableViewCell class] forCellReuseIdentifier:@"TeachClassTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(teachClassHeadView.mas_bottom).offset(10);
        
        make.left.width.bottom.mas_equalTo(self.view);
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    
    
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
    
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

/**
 加载数据
 */
-(void)loadData{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    VenueModel *venueModel = [VenueModel venue];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:self.date forKey:@"Date"];
    
    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:GET_CoursePlanListByDate parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  [self.noDataView hideInView:self.view];
                  
                  if (startIndex == 1) {
                      
                      self.dataSource = [NSMutableArray arrayWithArray:resultArray];
                      
                      if (self.dataSource.count == 0) {
                          
                          self.noDataView = [NoDataView shareInstance];
                          
                          [self.noDataView showInView:self.view];
                      }
                  }
                  else{
                      
                      [self.dataSource addObjectsFromArray:resultArray];
                  }
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark 设置 SelectDate
-(void)setSelectData:(NSNotification *)sender{
    
    NSDictionary *dict = sender.userInfo;
    
    NSString *date = [dict objectForKey:@"selectDate"];
    
    self.date = date;
    
    [self loadStartData];
}



#pragma mark UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

#pragma mark UITableViewDelegate
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TeachClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeachClassTableViewCell"];
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[dict objectForKey:@"Pic"],mid_image];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [cell.classImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
    
    cell.classNameLabel.text = [dict objectForKey:@"CourseName"];
    
    cell.placeNameLabel.text = [NSString stringWithFormat:@"上课场地：%@",[dict objectForKey:@"PlaceName"]];
    
    cell.teachLabel.text = [NSString stringWithFormat:@"讲课老师：%@",[dict objectForKey:@"TeacherName"]];
    
    NSString *BeginDateTime = [dict objectForKey:@"BeginDateTime"];
    
    //根据开始时间计算
    NSRange range = NSMakeRange(11, 5);
    
    NSString *key = [BeginDateTime substringWithRange:range];
    
    cell.timeLabel.text = key;
    
    NSString *endTime = [dict objectForKey:@"EndDateTime"];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    if ([self compareOneDay:BeginDateTime withAnotherDay:[dateFormatter stringFromDate:[NSDate date]]] > 0) {
        
        [cell.stateBtn setTitle:@"待上课"];
        [cell.stateBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
        cell.stateBtn.backgroundColor = ButtonBackGroundColor;
    }
    else if([self compareOneDay:BeginDateTime withAnotherDay:[dateFormatter stringFromDate:[NSDate date]]] < 0 && [self compareOneDay:endTime withAnotherDay:[dateFormatter stringFromDate:[NSDate date]]] > 0){
        
        [cell.stateBtn setTitle:@"进行中"];
        [cell.stateBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
        cell.stateBtn.backgroundColor = ButtonBackGroundColor;
    }
    else{
        
        [cell.stateBtn setTitle:@"已完成"];
        [cell.stateBtn setTitleColor:CSWhiteColor];
        cell.stateBtn.backgroundColor = CSColorFromRGBA(0xbdbdbd, 0.8);
    }
    
    cell.countLabel.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Orders"]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PointClassInfoViewController *pointClassInfoVC = [[PointClassInfoViewController alloc] init];
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    pointClassInfoVC.dict = dict;
    
    [self.navigationController pushViewController:pointClassInfoVC animated:YES];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

/**
 *  左滑cell时出现什么按钮
 */
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    __weak typeof(self)weakSelf = self;
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [weakSelf deleteClass:[dict objectForKey:@"ID"]];
        
        tableView.editing = NO;
    }];
    
    return @[action1];
}


#pragma mark 删除
-(void)deleteClass:(NSString *)classId{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"message:@"确定删除该排课?"preferredStyle:UIAlertControllerStyleAlert];
    
    //添加取消到UIAlertController中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:cancelAction];
    
    //添加确定到UIAlertController中
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [MBProgressHUD showMessage:@"删除中..." toView:self.view];
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        
        NSString *delUrl = [NSString stringWithFormat:@"%@/%@",Post_DeleteCoursePlan,classId];
        
        [HTTPTool POSTRaw:delUrl parameters:params success:^(id responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
                
                [MBProgressHUD showText:@"删除成功"];
                
                [NotificationCenter postNotificationName:@"ReloadWeekDay" object:nil];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            else{
                
                [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
            }
            
        } failure:^(NSError *error) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            [MBProgressHUD showText:@"删除失败"];
        }];
        
    }];
    
    [alertController addAction:OKAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}


-(int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay

{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];
    
    NSComparisonResult result = [dateA compare:dateB];
    
    //NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    
    if (result == NSOrderedDescending) {
        
        //NSLog(@"Date1  is in the future");
        
        return 1;
        
    }
    
    else if (result ==NSOrderedAscending){
        
        //NSLog(@"Date1 is in the past");
        
        return -1;
        
    }
    
    //NSLog(@"Both dates are the same");
    
    return 0;
    
}

-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}

@end
